import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  Drawer,
  DrawerProps,
  Form,
  FormProps,
  Input,
  InputNumber,
  Radio,
  Space,
  TreeSelect,
  TreeSelectProps
} from 'antd';

import { store } from '@/store';

import * as Enum from '@/enum/auth';
import { permissionApiTree } from '@/services/base/quanxianmokuaihouduanjiekouxinxijiekou';
import {
  permissionFrontAdd,
  permissionFrontUpdate
} from '@/services/base/quanxianmokuaiqianduanyemianquanxianguanli';
import { formatEnum } from '@/utils';

import { BizObject } from '.';

/** 根据节点id,新增跟级节点需要 */
const FE_ROOT_ID = 0;

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type DetailProps = {
  /** 前端权限列表 */
  feAuthTreeData: BizObject[];
};

const Edit: React.ForwardRefRenderFunction<EditRef, DetailProps> = ({ feAuthTreeData }, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  // 后端权限树
  const beTree = useRequest(
    async () => {
      const formatTree = (data: BASE.ApiPermission[]): TreeSelectProps['treeData'] => {
        return data.map((item) => {
          return {
            title: (
              <div>
                {formatEnum(item.permissionType, Enum.BeAuthTypeObj) as string}
                {formatEnum(item.status, Enum.BeAuthStatusObj) as string}
                {item.permissionName}
              </div>
            ),
            // 只能绑定接口
            disabled: item.permissionType !== Enum.BeAuthType.接口,
            value: item.apiCode,
            children: item.child ? formatTree(item.child) : undefined,

            data: item
          };
        });
      };

      const res = await permissionApiTree({});

      return formatTree(res.data || []);
    },
    {
      cacheKey: 'permissionApiTree'
    }
  );
  const submit = useRequest(
    async (values) => {
      const query = {
        ...values
      } as BASE.PagePermission;

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? permissionFrontUpdate(query) : permissionFrontAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  const afterOpenChange: DrawerProps['afterOpenChange'] = (open) => {
    if (open) {
      // 编辑回填数据
      if ((args?.type === 'edit' || args?.type === 'detail') && args?.rowData) {
        // 回填数据
        form.setFieldsValue({
          ...args.rowData,
          apiPermissions: (args.rowData?.apiList || []).map((v) => v.apiCode).filter(Boolean)
        });
      } else {
        form.resetFields();
        form.setFieldsValue({
          type: Enum.FeAuthType.端,
          status: Enum.FeAuthStatus.需要验证,
          sort: 0,
          pid: FE_ROOT_ID
        });
      }
    }
  };

  return (
    <Drawer
      title={
        {
          add: '新增菜单',
          edit: '编辑菜单',
          detail: '菜单详情'
        }[args?.type as string]
      }
      width="50%"
      open={open}
      afterOpenChange={afterOpenChange}
      onClose={onCancel}
      footer={
        args?.type === 'detail' ? null : (
          <Space>
            <Button
              type="primary"
              loading={submit.loading}
              disabled={submit.loading}
              onClick={form.submit}
            >
              保存
            </Button>
            <Button onClick={onCancel} disabled={submit.loading}>
              取消
            </Button>
          </Space>
        )
      }
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        labelWrap
      >
        <Form.Item
          label="上级权限"
          name="pid"
          rules={[{ required: true, message: '请选择上级权限' }]}
        >
          <TreeSelect
            treeDefaultExpandAll
            treeData={[
              {
                permissionName: '顶级权限',
                id: FE_ROOT_ID,
                child: feAuthTreeData
              }
            ]}
            fieldNames={{
              label: 'permissionName',
              value: 'id',
              children: 'child'
            }}
          />
        </Form.Item>
        <Form.Item
          label="权限名称"
          name="permissionName"
          rules={[
            {
              required: true,
              message: '请输入权限名称'
            }
          ]}
        >
          <Input placeholder="请输入权限名称" allowClear />
        </Form.Item>
        <Form.Item
          label="权限编码"
          name="permissionCode"
          rules={[
            {
              required: true,
              message: '请输入权限编码'
            }
          ]}
        >
          <Input placeholder="请输入权限编码" allowClear />
        </Form.Item>
        <Form.Item label="接口权限" name="apiPermissions">
          <TreeSelect
            showSearch
            treeDefaultExpandAll
            multiple
            treeCheckable
            showCheckedStrategy={TreeSelect.SHOW_ALL}
            filterTreeNode={(inputValue, treeNode) => {
              if (!inputValue) {
                return true;
              }

              return treeNode.data?.permissionName?.includes(inputValue);
            }}
            treeData={(beTree.data as unknown as {}[]) || []}
          />
        </Form.Item>
        <Form.Item
          label="类型"
          name="type"
          rules={[
            {
              required: true,
              message: '请选择类型'
            }
          ]}
        >
          <Radio.Group>
            {Array.from(Enum.FeAuthTypeObj).map(([key, value]) => {
              return (
                <Radio key={key} value={key}>
                  {value.text}
                </Radio>
              );
            })}
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="校验类型"
          name="status"
          rules={[
            {
              required: true,
              message: '请选择校验类型'
            }
          ]}
        >
          <Radio.Group>
            {Array.from(Enum.FeAuthStatusObj).map(([key, value]) => {
              return (
                <Radio key={key} value={key}>
                  {value.text}
                </Radio>
              );
            })}
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="排序"
          name="sort"
          rules={[
            {
              required: true,
              message: '请填写排序'
            }
          ]}
        >
          <InputNumber min={0} step={1} />
        </Form.Item>
        <Form.Item label="组件地址" name="componentUrl">
          <Input placeholder="请输入组件地址" allowClear />
        </Form.Item>
        <Form.Item label="说明" name="extend">
          <Input.TextArea placeholder="请输入说明" allowClear />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
